import { FC, useRef, useMemo } from 'react';
import styles from './index.module.scss';
import { Button, Input, Space, Typography, Tooltip, Popover, message, InputRef } from 'antd';
import useGetPageInfo from '../../../../../hooks/useGetPageInfo';
import { useNavigate, useParams } from 'react-router-dom';
import { CopyOutlined, LeftOutlined, QrcodeOutlined } from '@ant-design/icons';
import QRCode from 'qrcode.react';
const { Title } = Typography;

const StatHeader: FC = () => {
  const { title, isPublished } = useGetPageInfo();

  const { id } = useParams();
  const nav = useNavigate();
  const urlInputRef = useRef<InputRef>(null);
  function copy() {
    const inputElement = urlInputRef.current;
    if (inputElement) {
      inputElement.select();
      document.execCommand('copy');
      message.success('拷贝成功');
    }
  }

  // function genLinkAndQRCodeElement() {
  //   if (!isPublished) {
  //     return;
  //   }
  //   const url = `http://localhost:3000/question/${id}`;
  //   const QRCodeElement = (
  //     <div style={{ textAlign: 'center' }}>
  //       <QRCode value={url} size={150} />
  //     </div>
  //   );
  //   return (
  //     <Space>
  //       <Input value={url} style={{ width: '300px' }} ref={urlInputRef} />
  //       <Tooltip title="拷贝链接">
  //         <Button icon={<CopyOutlined />} onClick={() => copy()} />
  //       </Tooltip>
  //       <Popover content={QRCodeElement}>
  //         <Button icon={<QrcodeOutlined />} />
  //       </Popover>
  //     </Space>
  //   );
  // }

  const LinkAndQRCodeElement = useMemo(() => {
    if (!isPublished) {
      return;
    }
    const url = `http://localhost:3000/question/${id}`;
    const QRCodeElement = (
      <div style={{ textAlign: 'center' }}>
        <QRCode value={url} size={150} />
      </div>
    );
    return (
      <Space>
        <Input value={url} style={{ width: '300px' }} ref={urlInputRef} />
        <Tooltip title="拷贝链接">
          <Button icon={<CopyOutlined />} onClick={() => copy()} />
        </Tooltip>
        <Popover content={QRCodeElement}>
          <Button icon={<QrcodeOutlined />} />
        </Popover>
      </Space>
    );
  }, [id, isPublished]);

  return (
    <div className={styles['header-wrapper']}>
      <div className={styles.header}>
        <div className={styles.left}>
          <Space>
            <Button icon={<LeftOutlined />} type="link" onClick={() => nav(-1)}>
              返回
            </Button>
            <Title level={5}>{title}</Title>
          </Space>
        </div>
        <div className={styles.main}>{LinkAndQRCodeElement}</div>
        <div className={styles.right}>
          <Button type="primary" onClick={() => nav(`/question/edit/${id}`)}>
            编辑问卷
          </Button>
        </div>
      </div>
    </div>
  );
};

export default StatHeader;
